/*
Copyright 2010 Christian Dadswell
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package subscriber.chrisdadswell.co.uk;

import java.util.ArrayList;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.google.ads.AdSenseSpec;
import com.google.ads.GoogleAdView;
import com.google.ads.AdSenseSpec.AdType;

public class Activity_Subscriber extends Activity implements Runnable, OnSharedPreferenceChangeListener{

// VARS
    public static final String _APP_TAG = "Activity_Subscriber"; 
	static Context context;
	
	protected static final int DIALOG_TAGLIST = 1;
	protected static final int DIALOG_CONFIRMATION = 2;
	protected static final int DIALOG_ACCOUNTS = 3;
	
	public static int FirstRun = 0;
	public static int _RESULT_TAGS_FOUND = 0;
	public static int _RESULT_TAG_SHARE = 0;
	
	public static boolean _RESULT_AUTH = false;
	public static boolean _RESULT_TAGS = false;
	public static boolean _RESULT_SUBSCRIPTION = false;
	public static boolean _FETCH_TAGS_RUN = false;
	
	public static String _TOKEN = null;
	public static String _USERNAME = null;
	public static String _USERID = null;
	public static String _PASSWORD = null;
	public static String _FEED_URL = null;
	public static String _TAG_STRING = null;
	public static String _TAG_SHARE = "Private";
	private static String _FEED_TITLE = "<No Title Set>";
	public static String _TAG_TITLE = "Untagged";
	public static String _SET_ACCOUNT = null;
	
	static SharedPreferences _PREFS;
	private ProgressDialog PD;
	
	private FetchTagsTask ftTask = null;

	AdSenseSpec adSenseSpec = new AdSenseSpec("ca-mb-app-pub-7652034860255777")
    .setCompanyName("chrisdadswell.co.uk")
    .setAppName("Subscriber")
    .setAdType(AdType.IMAGE)
	.setAdTestEnabled(false);
	
// LIFECYCLES
	
	public void onStart() {
		super.onStart();
		Log.d(_APP_TAG, "---------- onStart");
		
		// SET GOOGLE ACCOUNT TO USE
		//showDialog(DIALOG_ACCOUNTS);

	Log.d(_APP_TAG, "LIFECYCLE: End of OnStart()");
	} // END OF ONSTART
		
	public void onRestart() {
		super.onRestart();
		Log.d(_APP_TAG, "---------- onRestart");
	}
	public void onResume() {
		super.onResume();
		Log.d(_APP_TAG, "---------- onResume");
	} 
	public void onPause() {
		super.onPause();
		Log.d(_APP_TAG, "---------- onPause");
	}
	public void onStop() {
		super.onStop();
		Log.d(_APP_TAG, "---------- onStop");
		Log.d(_APP_TAG, "VAR: FeedTitle = " + _FEED_TITLE + " FeedURL = " + _FEED_URL);
	}	
	public void onDestroy() {
		super.onDestroy();
		Log.d(_APP_TAG, "---------- onDestroy");
		Log.d(_APP_TAG, "VAR: FeedTitle = " + _FEED_TITLE + " FeedURL = " + _FEED_URL);
	}
	
// ONSTART METHODS	
	public boolean BundledFeedType(String FeedTitle, String FeedURL) {
		Log.d(_APP_TAG, "METHOD: BundledFeedType(" + FeedTitle +","+ FeedURL);
		int feedtitle = 0;
		int feedurl = 0;
		
		Log.d(_APP_TAG, "VAR: FeedTitle = "+ FeedTitle + " size = " + FeedTitle.length() +","+ FeedURL);
		
		if(FeedTitle != "<No Title>") {
			feedtitle = 1;
		}else{
			feedtitle = 0;
		}
		
		if(FeedURL != null) {
			feedurl = 1;
		}else{
			feedurl = 0;
		}
		
		if(feedtitle == 1 && feedurl == 1) {
			return true;
		}else if(feedtitle == 0 && feedurl == 1) {
			return false;
		}
		return false;
	}
	
// CREATE THE ACTIVITY
	
    public void onCreate(Bundle savedInstanceState) { 
    	super.onCreate(savedInstanceState); 
    	setContentView(R.layout.subscriber2);
    	getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
    	Log.d(_APP_TAG, "---------- onCreate");
        GoogleAdView adView = (GoogleAdView) findViewById(R.id.adview);
        adView.showAds(adSenseSpec);
    	context = this;
    	
    	ftTask = (FetchTagsTask) getLastNonConfigurationInstance();
    	
		if (ftTask==null) {
			ftTask = new FetchTagsTask(this);
		} else {
			ftTask.attach(this);
		}

		Log.d(_APP_TAG, "BUNDLE: Retrieving Bundle ...");
		Bundle intent_extras = getIntent().getExtras(); 
		if(intent_extras !=null) {
			_FEED_TITLE = intent_extras.getString("SelectedFeedTitle");
			_FEED_URL = intent_extras.getString("SelectedFeedURL");
			Log.d(_APP_TAG, "BUNDLE: FeedTitle = " + _FEED_TITLE + " FeedURL: " + _FEED_URL);
		}
		
		Log.d(_APP_TAG, "CALLING: BundledFeedType(" + _FEED_TITLE + "," + _FEED_URL);
		if(BundledFeedType(_FEED_TITLE, _FEED_URL)) { // TRUE = Site FALSE = Direct
			// TITLE AND URL PASSED
			Log.d(_APP_TAG, "RESPONSE: BundledFeedType = Site feed");
		}else{
			// ONLY URL PASSED
			Log.d(_APP_TAG, "RESPONSE: BundledFeedType = Direct feed");
			Log.d(_APP_TAG, "VARSET: _FEED_TITLE = <No Title Set>");
			_FEED_TITLE = "<No Title Set>";
		}

        
//INIT ACTIVITY WIDGETS
    	final EditText TXT_FEEDTITLE = (EditText)findViewById(R.id.txt_feedtitle);
    	TXT_FEEDTITLE.setText(_FEED_TITLE);
		
// INITIALIZE PREFERENCES
		_PREFS = PreferenceManager.getDefaultSharedPreferences(this);
		_PREFS.registerOnSharedPreferenceChangeListener(this);
		
// TAG LONG CLICK LISTENER
		final EditText TXT_TAGTITLE = (EditText)findViewById(R.id.txt_tag);
		TXT_TAGTITLE.setOnLongClickListener(new TextView.OnLongClickListener() {
        	public boolean onLongClick(View v) {
        		final Intent prefsActivity = new Intent(getBaseContext(), Activity_Preferences.class);
        		if(CheckCredentials()) {
        			if(_FETCH_TAGS_RUN) {
            			//removeDialog(DIALOG_TAGLIST);
            			showDialog(DIALOG_TAGLIST);
            		}else{
            			ftTask.execute(getUsername(),getPassword());
            			_FETCH_TAGS_RUN = true;
                		return true;
            		}
        		}else{
        			Log.d(_APP_TAG, "RESPONSE: No Credentials set, showing preferences");
	        		Toast.makeText(Activity_Subscriber.this, "\nNo credentials set, please enter them in Preferences and try again\n", Toast.LENGTH_SHORT).show();
	        		startActivity(prefsActivity);
        		}
        		return true;
        	}
        });
		
// QUICKADD SUBSCRIPTION
		Button BTN_SUBSCRIBE = (Button)findViewById(R.id.btn_quickadd);
        BTN_SUBSCRIBE.setOnClickListener(new Button.OnClickListener() {
        	public void onClick (View v){
				Log.d(_APP_TAG, "ACTION: Subscription Button Clicked");
				Log.d(_APP_TAG, "VARS: FeedTitle = " + _FEED_TITLE + " TagTitle = " + _TAG_TITLE);
				
				// ANY TEXT ENTERED OVERRIDES AUTOMATIC ENTRIES
				String _FEEDTITLE = TXT_FEEDTITLE.getText().toString();
				String _TAGTITLE = TXT_TAGTITLE.getText().toString();
				
				if (_FEEDTITLE != null && _FEEDTITLE.trim().length() == 0) {
					// NOTHING ENTERED IN TITLE TEXT, USE FEED TITLE RETURNED FROM FEED VALUE
					Log.d(_APP_TAG, "RESPONSE: Nothing set in FeedTitle EditText");			
					Log.d(_APP_TAG, "VARS: FeedTitle = " + _FEED_TITLE);
				}else{
					// USE ENTERED TEXT IN EDITTEXT
					Log.d(_APP_TAG, "RESPONSE: Text set in FeedTitle EditText");
					_FEED_TITLE = _FEEDTITLE;
					Log.d(_APP_TAG, "VARS: FeedTitle = " + _FEED_TITLE);
				}
				
				// TAG TITLE
				if (_TAGTITLE != null && _TAGTITLE.trim().length() == 0) {
					// NOTHING ENTERED IN TAG TEXT
					Log.d(_APP_TAG, "RESPONSE: Nothing set in TagTitle EditText, checking _TAG_TITLE var...");
					if(_TAG_TITLE == "Untagged") {
						_TAG_TITLE = "Untagged";
						Log.d(_APP_TAG, "VARS: TagTitle = " + _TAG_TITLE);
					}else{
						
					}
				}else{
					// USE ENTERED TEXT IN EDITTEXT
					Log.d(_APP_TAG, "RESPONSE: Text set in TagTitle EditText");
					_TAG_TITLE = _TAGTITLE;
					Log.d(_APP_TAG, "VARS: FeedTitle = " + _TAG_TITLE);
				}
				
				if(_FEED_URL != null) {
					removeDialog(DIALOG_CONFIRMATION);
					showDialog(DIALOG_CONFIRMATION);
					_FEEDTITLE = null;
					_TAGTITLE = null;
				}else{
					// NO FEED URL
					Toast.makeText(Activity_Subscriber.this, "\nNo feed was selected to subscribe to." +
							"\n\nHit the back button and try again.\n", 
							Toast.LENGTH_LONG).show();
				}
				Log.d(_APP_TAG, "VARS: Feedtitle = " + _FEEDTITLE + " : Tagtitle = " + _TAGTITLE);
				Log.d(_APP_TAG, "LOCAL VARS: FeedTitle = " + _FEED_TITLE + " TagTitle = " + _TAG_TITLE);
        	}
        });
       
// TAG SHARE CHECKBOX
        final CheckBox CHK_SHARE = (CheckBox)findViewById(R.id.chk_share);
        CHK_SHARE.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked) {
                	Log.d(_APP_TAG, "ACTION: Tag Sharing Public");
                	CHK_SHARE.setText("Untick to mark Tag Private?");
                	_TAG_SHARE = "Public";
                }else{
                	Log.d(_APP_TAG, "ACTION: Tag Sharing Private");
                	CHK_SHARE.setText("Tick to mark Tag Public?");
                	_TAG_SHARE = "Private";   
                }
            }
        });
        
    }// END OF ONCREATE
    
    @Override
	public Object onRetainNonConfigurationInstance() {
		ftTask.detach();
		return(ftTask);
	}
    
    static class FetchTagsTask extends AsyncTask<String, Void, Boolean> {
    	private ProgressDialog PD = new ProgressDialog(context);
    	Activity_Subscriber activity=null;
    	
    	FetchTagsTask(Activity_Subscriber activity) {
			attach(activity);
		}
    	
    	protected void onPreExecute() {
    		PD.setMessage("\n\nFetching Google Reader Tags ...\n\n");
    		PD.show();
    	}
    	
    	@Override
		protected Boolean doInBackground(String... params) {
			Log.d(_APP_TAG, "ASYNCTASK: doInBackground(Func_JSOUP.tagsInReader)");
			boolean _RESULT_TAGS_FOUND = Func_JSOUP.tagsInReader(getUsername(), getPassword());
			return _RESULT_TAGS_FOUND;
		}
    	
		@Override
		protected void onProgressUpdate(Void... unused) {
		}
		
		@Override
		protected void onPostExecute(Boolean _RESULT_FEED_FOUND) {
			if(_RESULT_FEED_FOUND) {
				activity.showDialog(DIALOG_TAGLIST);
				if (PD.isShowing()) {
					PD.dismiss();
				}
			}else{
				Toast.makeText(context, "\nNo Tags found in Google Reader\n", Toast.LENGTH_SHORT).show();
				PD.dismiss();
				activity.finish();
			}
		}
		
		void detach() {
			_FETCH_TAGS_RUN = true;
			activity=null;
		}

		void attach(Activity_Subscriber activitySubscriber) {
			this.activity = activitySubscriber;
		}
    } // END OF AYSNCTASK
    
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		Log.d(_APP_TAG, "CALLING: CheckCredentials()");
	}
	
	private static String getUsername() {
		_USERNAME = _PREFS.getString("prefGoogleUser", "").toString().trim();	
		Log.d(_APP_TAG, "VAR: Username set");
		return _USERNAME;
	}
	
	private static String getPassword() {
		_PASSWORD = _PREFS.getString("prefGooglePassword", "").toString().trim();
		Log.d(_APP_TAG, "VAR: Password set");
		return _PASSWORD;
	}
	
	private boolean CheckCredentials() {
		Log.d(_APP_TAG, "METHOD: CheckCredentials()");
		int usercheck = 0;
		int passcheck = 0;
		
		usercheck = CheckForUsername();
		passcheck = CheckForPassword();

		if(usercheck == 0 && passcheck == 0) {
			Toast.makeText(Activity_Subscriber.this, "\nPlease set your Google username and password\n", Toast.LENGTH_SHORT).show();
			return false;
		}else if(usercheck == 1 && passcheck == 0) {
			Toast.makeText(Activity_Subscriber.this, "\nPlease set your Google password\n", Toast.LENGTH_SHORT).show();
			return false;
		}else if(usercheck == 0 && passcheck == 1) {
			Toast.makeText(Activity_Subscriber.this, "\nPlease set your Google username\n", Toast.LENGTH_SHORT).show();
			return false;
		}else if(usercheck == 1 && passcheck == 1) {
			return true;
		}
		return false;
	}
	
	static int CheckForUsername() {
	    _USERNAME = getUsername();
	    if(_USERNAME == "Nothing"){
			return 0;
		}else if (_USERNAME != null && _USERNAME.trim().length() == 0) {
        	return 0;
        }else
        	return 1;
	}
	
	static int CheckForPassword() {
	    _PASSWORD = getPassword();
		if (_PASSWORD != null && _PASSWORD.trim().length() == 0) {
        	return 0;
        }else
        	return 1;
		}
	

// DIALOGS
    protected Dialog onCreateDialog(int id) {
    	Log.d(_APP_TAG, "DIALOG: " + id);
    	final Intent prefsActivity = new Intent(getBaseContext(), Activity_Preferences.class);
    	Dialog dialog;
    	switch (id) {
            
    	case DIALOG_ACCOUNTS:
    		final String _ACCOUNTS[] = getGoogleAccounts();
    		if (_ACCOUNTS.length == 0) {
    			
    		}else{
    			AlertDialog.Builder accounts_dialog = new AlertDialog.Builder(this);
        		accounts_dialog.setTitle("Available Accounts");
            	accounts_dialog.setItems(_ACCOUNTS, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    	_SET_ACCOUNT = _ACCOUNTS[which];
                    	Log.d(_APP_TAG, "VAR: TagTitle = " + _TAG_TITLE);
                    	dialog.dismiss();              	
                    	return;
                    }
                });
                AlertDialog accounts_alert = accounts_dialog.create();
                return accounts_alert;
    		}
    		
        case DIALOG_TAGLIST:
        	final String[] _TAG_TITLES  = Func_JSOUP.getTagList(getUsername(), getPassword());
        	AlertDialog.Builder tags_dialog = new AlertDialog.Builder(this);
        	tags_dialog.setTitle("Available Tags");
        	tags_dialog.setItems(_TAG_TITLES, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                	_TAG_TITLE = _TAG_TITLES[which];
                	Log.d(_APP_TAG, "VAR: TagTitle = " + _TAG_TITLE);
                	dialog.dismiss();
                	return;
                }
            });
        	
            tags_dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					Log.d(_APP_TAG, "ACTION: I've been cancelled!");
				}
			});
        	
            AlertDialog tags_alert = tags_dialog.create();
            return tags_alert;
            
        case DIALOG_CONFIRMATION:
        	AlertDialog.Builder conf_dialog = new AlertDialog.Builder(this);
    		conf_dialog.setIcon(R.drawable.subscriber);
    		conf_dialog.setMessage("Subscription Details\n\n" +
    				"Feed title: " + _FEED_TITLE + "\n" + "Tag title: " + _TAG_TITLE + "\n" + "Tag sharing: " +
    						_TAG_SHARE + "\n\n" + "Subscribe with these options?")
    		       .setCancelable(false)
    		       .setPositiveButton("Subscribe", new DialogInterface.OnClickListener() {
    		           public void onClick(DialogInterface dialog, int id) {
    		        	   if(CheckCredentials()) {
    		        		   // CREDS SET
    		        		   Log.d(_APP_TAG, "CALLING: Subscription_Thread(" + _FEED_TITLE + "," + _TAG_TITLE);
    		        		   Subscription_Thread(_FEED_TITLE, _TAG_TITLE);
    		        	   }else{
    		        		   // CREDS NOT SET
    		        		   Log.d(_APP_TAG, "RESPONSE: No Credentials set, showing preferences");
    		        		   Toast.makeText(Activity_Subscriber.this, "\nNo credentials set, please enter them in Preferences and try again\n", Toast.LENGTH_SHORT).show();
    		        		   startActivity(prefsActivity);
    		        	   }
    		        	   if(_TAG_SHARE == "Public") {
    		        		   Log.d(_APP_TAG, "CALLING: Tagshare_Thread(" + _TAG_SHARE + ")");
    		        		   Tagshare_Thread(_TAG_SHARE);
    		        	   }else{}
    		           }
    		       })
    		       .setNeutralButton("Feed Details", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Toast.makeText(Activity_Subscriber.this, "\nFeed Title: " + _FEED_TITLE + "\n\n" +
								"Feed URL: " + _FEED_URL + "\n\n" +
										"Tag Title: " + _TAG_TITLE, Toast.LENGTH_LONG).show();
					}
    		       })
    		       
    		       .setNegativeButton("Back", new DialogInterface.OnClickListener() {
    		    	   public void onClick(DialogInterface dialog, int id) {
    		    		   dialog.cancel();
    		    	   }
    		       });
    		AlertDialog conf_alert = conf_dialog.create();
    		return conf_alert;
    		
        default:
        	Log.d(_APP_TAG, "ACTION: Setting Confirmation Dialog to null");
        	dialog = null;
    	}
		return super.onCreateDialog(id);
    }
	
	private String[] getGoogleAccounts() {
        ArrayList<String> accountNames = new ArrayList<String>();
        Account[] accounts = AccountManager.get(this).getAccounts();
        for (Account account : accounts) {
            if (account.type.equals("com.google")) {
                accountNames.add(account.name);
            }
        }

        String[] result = new String[accountNames.size()];
        accountNames.toArray(result);
        return result;
    }

	// OPTIONS MENU
	
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		menu.add(0,Constants.MENU_PREFERENCES,0,"Subscriber Settings").setIcon(R.drawable.preferences);
		return super.onPrepareOptionsMenu(menu);
	}// END OF OPTIONS MENU
		
	@Override
	public boolean onOptionsItemSelected (MenuItem item){
		switch (item.getItemId()){
		case Constants.MENU_PREFERENCES:
			Intent prefsActivity = new Intent(getBaseContext(), Activity_Preferences.class);
			startActivity(prefsActivity);
			break;
		}
		return false;
	}// END OF OPTIONS SELECTED
	
// THREADS 
    
	private void Subscription_Thread(String FeedTitle, final String TagTitle) {
		Log.d(_APP_TAG, "METHOD: Subscription_Thread(" + FeedTitle + "," + TagTitle + ")");
		final String _TAG_TITLE = TagTitle;
		final String _FEED_TITLE = FeedTitle;
		String _PDMSG = null;
		
		Log.d(_APP_TAG, "VAR: FeedURL = " + _FEED_URL);
		
		if(_TAG_SHARE == "Private") {
			_PDMSG = "\nAttempting to subscribe feed: \n\n" + _FEED_TITLE + "\n\ninto a Private Tag: \n\n" + _TAG_TITLE + "\n";
		}else{
			_PDMSG = "\nAttempting to subscribe feed: \n\n" + _FEED_TITLE + "\n\ninto a Public Tag: \n\n " + _TAG_TITLE + "\n";
		}
		
		PD = ProgressDialog.show(Activity_Subscriber.this, "", _PDMSG, true, false);
			new Thread() {
				public void run() {
	   				try{
	   					//Log.d(_APP_TAG, "CALLING: Func_JSOUP.Subscription(subscribe," + _FEED_URL + "," + _FEED_TITLE + "," + _TAG_TITLE + ",USERNAME,PASSWORD");
	   					//if(Func_JSOUP.Subscription("subscribe", _FEED_URL, _FEED_TITLE, _TAG_TITLE, getUsername(), getPassword())) {
	   					Log.d(_APP_TAG, "CALLING: Func_GoogleReader.Subscription(subscribe," + _FEED_URL + "," + _FEED_TITLE + "," + _TAG_TITLE + ",USERNAME,PASSWORD");
	   		            if(Func_GoogleReader.Subscription("subscribe", _FEED_URL, _FEED_TITLE, _TAG_TITLE, getUsername(), getPassword())) {
	   						Log.d(_APP_TAG, "RESPONSE: Subscription Result = true");
	   						_RESULT_SUBSCRIPTION = true; 
	   					}else{
	   						Log.d(_APP_TAG, "RESPONSE: Subscription Result = false");
	   						_RESULT_SUBSCRIPTION = false;
	   					}
	   				} catch (Exception e) {  }
	   				Handler_Subscription.sendEmptyMessage(0);
	   				Log.d(_APP_TAG, "ACTION: Dismissing Subscribe Dialog");
	   				PD.dismiss();               
	   				}
	   		}.start();		
	}

// SUB HANDLER
	private Handler Handler_Subscription = new Handler() {
		public void handleMessage(Message msg) {
			if(_RESULT_SUBSCRIPTION == true) {
				Toast.makeText(Activity_Subscriber.this, "\nSubscription Successful!\n", Toast.LENGTH_SHORT).show();
				finish();
			}else{
				Toast.makeText(Activity_Subscriber.this, "\nSubscription Unsuccessful!\n\n" +
						"Please check your credentials are correct in Preferences and try again\n\n" +
						"If the subscription fails again, the feed URL may be incorrect in some way.\n", Toast.LENGTH_LONG).show();
			}
		}
	};
	
	private void Authentication_Thread() {
		Log.d(_APP_TAG, "METHOD: Authentication_Thread()");
		new Thread() {
			public void run() {
   				try{
   					Log.d(_APP_TAG, "CALLING: Func_JSOUP.getGoogleUserID()");
   					_USERID = Func_JSOUP.getGoogleUserID(getUsername(), getPassword());
   					Log.d(_APP_TAG, "UserID: " + _USERID);
   					if(_USERID != null) {
   						Log.d(_APP_TAG, "RESPONSE: Auth Result = true");
   						_RESULT_AUTH = true;
   					}else{
   						Log.d(_APP_TAG, "RESPONSE: Auth Result = false");
   						_RESULT_AUTH = false;
   					}
   				} catch (Exception e) {  }
   				Handler_Authentication.sendEmptyMessage(0);
   				}
   		}.start();	
	}

	private Handler Handler_Authentication = new Handler() {
		public void handleMessage(Message msg) {
			if(_RESULT_AUTH == true) {
				Toast.makeText(Activity_Subscriber.this, "\nGoogle authentication successful!\n", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(Activity_Subscriber.this, "\nGoogle authentication failed!\n\nPlease check your Google credentials by launching Subscriber and pressing the MENU button.\n", Toast.LENGTH_SHORT).show();
			}
		}
	};
	    
	private void Tagshare_Thread(String ShareType) {
		_TAG_SHARE = ShareType;
		Log.d(_APP_TAG, "METHOD: Tagshare_Thread");
		Log.d(_APP_TAG, "VARS: USERNAME, PASSWORD" + "," + _USERID + "," + _TAG_TITLE + "," + _TAG_SHARE);
		if(_TAG_TITLE == "Untagged") {
			// NOT MARKING
		}else{
			//PD = ProgressDialog.show(Activity_Subscriber.this, "", "\nMarking Tag " + _TAG_TITLE + " Public ...\n", true, false);
	   		new Thread() {
				public void run() {
					try{
						Log.d(_APP_TAG, "CALLING: Func_JSOUP.tagShare()");
	   					if(Func_JSOUP.tagShare(getUsername(), getPassword(), 
	   							Func_JSOUP.getGoogleUserID(getUsername(), getPassword()),
	   							_TAG_TITLE, _TAG_SHARE)) {
	   						_RESULT_TAG_SHARE = 1;
	   						Log.d(_APP_TAG, "RESPONSE: TagShare Result = true");
	   					}else{
	   						_RESULT_TAG_SHARE = 0;
	   						Log.d(_APP_TAG, "RESPONSE: TagShare Result = false");
	   					}
	   				} catch (Exception e) { }
	   				Handler_Tagshare.sendEmptyMessage(0);
	   				Log.d(_APP_TAG, "ACTION: Dismissing TagShare Dialog");
	   				PD.dismiss();           
				}
	   		}.start();		
		}
	}

	private Handler Handler_Tagshare = new Handler() {
		public void handleMessage(Message msg) {
			if(_RESULT_TAG_SHARE == 1) {
				Toast.makeText(getBaseContext(), "\n'" + _TAG_TITLE + "' tag has been marked " + _TAG_SHARE + "\n", Toast.LENGTH_LONG).show();
			}else{
				Toast.makeText(getBaseContext(), "\n'" + _TAG_TITLE + "' could not be marked " + _TAG_SHARE + "\n", Toast.LENGTH_LONG).show();
			}
		}
	};

	
	@Override
	public void run() {}
} // END OF CLASS